<!-- 调整图片居中，https://yihui.name/js/center-img.js -->
<script>
// 获取元素绝对值left
function getLeft(e){
  var x = 0;
  while(e.offsetParent) {
    x+=e.offsetLeft;
    e=e.offsetParent;
  };
  return(x)
};

function img_zoom(img_selector) {
  // 图片放大 //////////////////////
  // 添加div
  bd = document.querySelector('body');
  bd.insertAdjacentHTML('beforeend', '<div class="imgzoom"></div>');
  imgzoom = document.querySelector('.imgzoom');
  imgzoom.style.display = "none";

  var imgsObj = document.querySelectorAll(img_selector);
  if (imgsObj) {
    Array.prototype.forEach.call(imgsObj,
    function(item) {
      item.onclick = function() {
        imgzoom.appendChild(item.cloneNode());
        imgzoom.style.display = "flex";
        var styleelm = document.createElement('style');
        styleelm.innerHTML = '.imgzoom{ position:fixed; top:0;left:0; width:100vw; height: 100vh; background-color: #eee;justify-content:center; align-items:center;}';
        document.querySelector('head').appendChild(styleelm);
      };
    });
  };

  imgzoom.onclick = function() {
    imgzoom.innerHTML = '';
    imgzoom.style.display = "none";
  };
}

function center_el(tagName) {
  var w = window.screen.width;
  var tags = document.getElementsByTagName(tagName), i, tag;
  for (i = 0; i < tags.length; i++) {
    tag = tags[i];
    var parent = tag.parentElement;
    // center an image if it is the only element of its parent
    if (parent.childNodes.length === 1) {
      // if there is a link on image, check grandparent
      if (parent.nodeName === 'A') {
        parent = parent.parentElement;
        if (parent.childNodes.length != 1) continue;
        parent.firstChild.style.border = 'none';
      }
      if (parent.nodeName === 'P') {
        parent.setAttribute('class', 'pimg');
        if(w<=480){
          // 让图片宽度布满屏幕
          tag.style.marginLeft="1px";
          tag.style.paddingLeft="0px";
          tag.style.maxWidth="100vw";
          tag.style.width="calc(100vw - 2px)";
          left=getLeft(tag);
          console.log("left = ", left);
          tag.style.marginLeft="-"+left+"px";
        } else {
          parent.style.textAlign = 'center';
        };
      };
    }
  }
}

(function() {

  var tagNames = ['img', 'embed', 'object'];
  for (var i = 0; i < tagNames.length; i++) {
    center_el(tagNames[i]);
  };
  
  img_zoom('p > img');

})();

</script><!-- END -->

